#include "ads7867.h"

#include "std.h"

t_ads7867 ads7867_dev[2];

void ads7867_init(p_ads7867 dev, uint8_t chan, SPI_HandleTypeDef *spix, GPIO_TypeDef *gpio_cs, uint16_t gpio_pin_cs, GPIO_PinState cs_valid)
{
    dev->chan = chan;

    dev->spix = spix;

    dev->gpio_cs = gpio_cs;
    dev->gpio_pin_cs = gpio_pin_cs;
    dev->cs_valid = cs_valid;
}

uint16_t ads7867_read(p_ads7867 dev)
{
    int tmp;
    uint8_t tx_buf[2], rx_buf[2];

    HAL_GPIO_WritePin(dev->gpio_cs, dev->gpio_pin_cs, dev->cs_valid);

    tx_buf[0] = 0xff;
    tx_buf[1] = 0xff;

    tmp = HAL_SPI_TransmitReceive(dev->spix, tx_buf, rx_buf, 2, 1000);
    if (tmp == HAL_OK)
    {
        dev->data = (rx_buf[0] << 8) | (rx_buf[1]);
    }

    HAL_GPIO_WritePin(dev->gpio_cs, dev->gpio_pin_cs, (GPIO_PinState)(!(dev->cs_valid)));

    return tmp;
}
